<?php

namespace App\Http\Controllers;

use App\Models\AdminMenusModel;
use App\Models\AdminRolesModel;
use App\Models\AdminUsersModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class LoginController extends BaseController
{

    protected $rule = [
        'loginname' => 'required|regex:/^[a-zA-Z][a-zA-Z0-9_]{3,20}$/',
        'password' => 'required',
        'captcha' => 'required|captcha',
    ];

    protected $message = [];

    public function __construct()
    {
        $this->message = [
            'loginname.required' => trans('login.login_required'),
            'loginname.regex' => trans('login.login_regex'),
            'password.required' => trans('login.password_is_empty'),
            'captcha.required' => trans('login.captcha_empty'),
            'captcha.captcha' => trans('login.captcha_captcha'),
        ];
    }

    public function index(Request $request)
    {
        return view('login.index');
    }

    /**
     * 处理登录操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function dologin(Request $request)
    {
        if (!$request->ajax()) {
            $this->_failed(trans('common.illegal_request'));
        }
        $data = $request->input();
        $validator = Validator::make($data, $this->rule, $this->message);
        if (!$validator->passes()) {
            return $this->_failed($validator->errors()->first());
        }
        $user = AdminUsersModel::getAdminUsersData(['loginname' => $data['loginname']]);
        if (is_null($user)) {
            return $this->_failed(trans('login.illegal_user'));
        }
        if ($user->status == AdminUsersModel::USERSDISABLE) {
            return $this->_failed(trans('login.user_disabled'));
        }
        if ($user->password != sha1($data['password'] . $user->salt)) {
            return $this->_failed(trans('login.password_error'));
        }
        if ($user->roles == "") {
            return $this->_failed(trans('login.no_role'));
        }
        if (!AdminUsersModel::updateAdminUsers(['id' => $user->id], ['last_login_time' => time()])) {
            return $this->_failed(trans('login.login_failed'));
        }
        $sessionUserData = array('id' => $user->id, 'loginname' => $user->loginname);
        $request->session()->put('userinfo', $sessionUserData);
        return $this->_success(['url' => $this->getRedirectUrl($user->id)]);
    }


    /**
     * 获取跳转页面
     * @param $uid
     * @return mixed|string
     */
    private function getRedirectUrl($uid)
    {
        $redirectUrl = "405";
        $user = AdminUsersModel::getAdminUsersData(['id' => $uid]);
        if ($user->roles == AdminUsersModel::SUPERUSERS) { //超级管理员
            $menus = AdminMenusModel::getAllAdminMenusForLeftMenu(['is_not_btn' => AdminMenusModel::BUTTON]);
        } else {
            $premission = "";
            $premissionIds = [];
            $role = AdminRolesModel::getAdminRoleData(['id' => $user->roles, 'status' => AdminRolesModel::ROLEENABLE]);
            if (!is_null($role)) {
                $premission = $role->premission;
            }
            if (!empty($premission)) {
                if ($premission != AdminRolesModel::SUPERROLE) {
                    if (strpos($premission, ",") !== false) {
                        $premissionIds = array_filter(explode(",", $premission));
                    } else {
                        $premissionIds = array($premission);
                    }
                }
                $menus = AdminMenusModel::getAllAdminMenusForLeftMenu([
                    'is_not_btn' => AdminMenusModel::BUTTON,
                    'status' => AdminMenusModel::MENUSHOW,
                    'id' => $premissionIds
                ]);
            }
        }
        $menus = !empty($menus) ? array_values($menus) : array();
        if (!empty($menus[0]['child'][0]['child'][0]['rule'])) {
            $redirectUrl = $menus[0]['child'][0]['child'][0]['rule'];
        }
        return $redirectUrl;
    }


    public function logout(Request $request)
    {
        $request->session()->flush();
        return redirect('/');
    }
}
